﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;

namespace PalmAddressExtractor
{
	public partial class MainWindow : Form
	{
		public MainWindow()
		{
			InitializeComponent();
		}

		#region Button event handler & helper methods
		
		private void ButtonSelectInput_Click(object sender, EventArgs e)
		{
			if (openInputDialog.ShowDialog() == System.Windows.Forms.DialogResult.OK)
				textSelectedInput.Text = openInputDialog.FileName;
		}

		private void ButtonSelectOutput_Click(object sender, EventArgs e)
		{
			if (saveOutputDialog.ShowDialog() == System.Windows.Forms.DialogResult.OK)
				textSelectedOutput.Text = saveOutputDialog.FileName;
		}

		private void ButtonProcess_Click(object sender, EventArgs e)
		{
			if (string.IsNullOrWhiteSpace(textSelectedInput.Text))
			{
				MessageBox.Show("You must select an input file.", "No input file selected", MessageBoxButtons.OK);
				return;
			}

			if (string.IsNullOrWhiteSpace(textSelectedOutput.Text))
			{
				MessageBox.Show("You must select an export file.", "No export file selected", MessageBoxButtons.OK);
				return;
			}

			buttonProcess.Enabled = false;
			fileProcessor.RunWorkerAsync(new Tuple<string, string>(textSelectedInput.Text, textSelectedOutput.Text));
			buttonCancel.Enabled = true;
		}

		private void ButtonCancel_Click(object sender, EventArgs e)
		{
			fileProcessor.CancelAsync();
		}

		#endregion

		private void FileProcessor_DoWork(object sender, DoWorkEventArgs e)
		{
			var fileNames = e.Argument as Tuple<string, string>;

			var inputFileStream = File.OpenRead(fileNames.Item1);
			var outputFileStream = File.Open(fileNames.Item2, FileMode.Create, FileAccess.Write, FileShare.None);

			var addressReader = new AddressReader(inputFileStream);
			var streamWriter = new StreamWriter(outputFileStream);

			var book = addressReader.ReadAddressBook();

			streamWriter.WriteLine(Address.GetDelimitedHeaders(","));
			for (var addressLoop = 0; addressLoop < book.Addresses.Count; addressLoop++)
			{
				streamWriter.WriteLine(book.Addresses[addressLoop].ToDelimitedString(","));
				fileProcessor.ReportProgress((int)(((double)addressLoop / (double)book.Addresses.Count) * 100));
			}

			streamWriter.Close();
			inputFileStream.Close();
		}

		private void FileProcessor_ProgressChanged(object sender, ProgressChangedEventArgs e)
		{
			progressBar.Value = e.ProgressPercentage;
		}

		private void FileProcessor_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
		{
			progressBar.Value = 100;

			buttonProcess.Enabled = true;
			buttonCancel.Enabled = false;
		}
	}
}
